'use strict';

const router = require('koa-router')();
const fs = require('fs');

//获取路由文件
function getRouteFiles(filePath) {

    let tmpPath = filePath || __dirname;

    let files = fs.readdirSync(tmpPath);

    let routeFiles = files.filter(item => {
        return item.endsWith('.js') && item !== 'index.js';
    });
    return routeFiles;
}

//编写路由规则
function registerRoute(router, routeFiles) {
    routeFiles.forEach(item => {
        let tmpPath = __dirname + '/' + item;
        let obj = require(tmpPath);
        for (let key in obj) {
            let tmpArr = key.split(' ');
            let routeUrl = tmpArr[1];
            let routeMethod = tmpArr[0];
            let routeFunction = obj[key];
            if (routeMethod === 'get') {
                router.get(routeUrl, routeFunction);
            } else if (routeMethod === 'post') {
                router.post(routeUrl, routeFunction);
            } else if (routeMethod === 'put') {
                router.put(routeUrl, routeFunction);
            } else if (routeMethod === 'delete') {
                router.delete(routeUrl, routeFunction);
            } else {

            }
        }
    });
    return router.routes();
}
//暴露
module.exports = function () {
    let routeFiles = getRouteFiles();
    let fn = registerRoute(router, routeFiles);
    return fn;
};